/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.thingsgrid.notice.feign;

import com.alibaba.fastjson.JSON;
import com.thingsgrid.notice.config.IMqttSender;
import com.thingsgrid.notice.config.MqttConfig;
import com.thingsgrid.notice.entity.NoticeEntiy;
import com.thingsgrid.notice.entity.SendEntiy;
import com.thingsgrid.notice.exception.NoticeException;
import com.thingsgrid.notice.service.InsService;
import com.thingsgrid.system.user.feign.IUserClient;
import lombok.AllArgsConstructor;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * Notice Feign
 *
 * @author Chill
 */
@ApiIgnore()
@RestController
@AllArgsConstructor
public class NoticeClient implements INoticeClient {

    private MqttConfig mqttConfig;
    private IMqttSender iMqttSender;
    private InsService<NoticeEntiy,SendEntiy> iSaveService;
    private IUserClient iUserClient;
    private final String type = "0";
    @Override
    public R sendMsg(String msgType, String sendType, String title, String content, String receiverName) {
        BladeUser user = SecureUtil.getUser();
        try{
            NoticeEntiy noticeEntiy = iSaveService.save(new NoticeEntiy(title,content,sendType,user.getAccount(),msgType),new SendEntiy(receiverName));
            if(type.equals(sendType)){
                iMqttSender.sendToMqtt(mqttConfig.getSystemTopic(),content);
            }else{
                String []receiverNames =  receiverName.split(",");
                for(String rname : receiverNames){
                    iMqttSender.sendToMqtt(rname,JSON.toJSONString(noticeEntiy));
                }
            }
            return R.success("OK");
        }catch (NoticeException e){
            return R.success(e.getR().getMsg());
        }

    }
}
